(function(){
	var obj_has = require("../_include/obj_con").has;
	//数据缓存文件
	var _db = require("./data.cache.json");
	//索引缓存文件
	var _index = require("./index.cache.json");
	var _ti;
	var foo = {
		_updateCache:function(){
			clearTimeout(_ti);
			_ti = setTimeout(function(){
				require("fs").writeFileSync(__dirname+"/data.cache.json",JSON.stringify(_db));
				require("fs").writeFileSync(__dirname+"/index.cache.json",JSON.stringify(_index));
			});
		},
		insert:function(db_name,obj,index){
			db_name = db_name.toLowerCase();
			var table = _db[db_name];
			if (!table) {
				table = _db[db_name] = []
				//索引
				_index[db_name] = table._ = {};
			}
			var table_index = _index[db_name]
			table.push(obj);
			if (obj._id||(obj._id = index)) {
				table_index[obj._id] = obj;
			}
			foo._updateCache(/*缓存到JSON文件中*/);
		},
		find_by_id:function(db_name,id){
			db_name = db_name.toLowerCase();
			var table_index = _index[db_name];
			if (table_index) {
				return table_index[id];
			}
		},
		find_one:function(db_name,obj){
			db_name = db_name.toLowerCase();
			var table = _db[db_name];
			var result;
			if (table instanceof Array) {
				table.every(function(item_obj){
					if (obj_has(item_obj, obj)) {
						result = item_obj;
					}else{
						return true;
					}
				});
			}
			return result;
		},
		find_list:function(db_name,obj){
			db_name = db_name.toLowerCase();
			var table = _db[db_name];
			var result = [];
			if (table instanceof Array) {
				table.forEach(function(item_obj){
					if (obj_has(item_obj, obj)) {
						result.push(item_obj)
					}
				});
			}
			return result;
		},
		find_all:function(db_name){
			db_name = db_name.toLowerCase();
			return _db[db_name]||[];
		},
		update:function(db_name,obj_index,obj){
			db_name = db_name.toLowerCase();
			var old_obj = foo.find_by_id(db_name,obj_index);
			if (old_obj) {
				for(var key in obj){
					old_obj[key] = obj[key];
				}
				//更新索引的对象
				_index[old_obj._id] = old_obj;
				foo._updateCache(/*缓存到JSON文件中*/);
			}else{
				foo.insert(db_name,obj,obj_index);
			}
		},
		remove:function(db_name,obj_index){
			db_name = db_name.toLowerCase();
			var table = _db[db_name];
			var remover;
			table.every(function(obj,index){
				if (obj._id === obj_index) {
					remover = obj;
					table.splice(index,1);
					return false;
				}
				return true;
			});
			if (remover) {
				delete _index[db_name][obj_index];
				foo._updateCache(/*缓存到JSON文件中*/);
			}
		},
		remove_list:function(db_name,obj){
			var remover_list = foo.find_list(db_name,obj);
			remover_list.forEach(function(remover){
				foo.remove(db_name,remover._id);
			});
		},
		refreshIndex:function(){
			_index = {};
			for(var dbname in _db){
				var table = _index[dbname] = {};
				_db[dbname].forEach(function(obj){
					table[obj._id] = obj;
				});
			}
			foo._updateCache(/*缓存到JSON文件中*/);
		}
	}
	module.exports = foo;
}());